/* 
 * Copyright 2013 Imanuel Rohlfing, Dennis Wittkötter

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package management.beans;

import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import management.constants.Names;
import management.ejb.DatabaseController;
import management.entities.IntUser;


/**
 * Bean for login procedure.
 * @author Imanuel Rohlfing
 */
@ManagedBean(name="auth")
@SessionScoped
public class LoginBean implements Serializable{
    
    /**
     * database controller
     */
    @EJB
    private DatabaseController dbC;
    
    /**
     * current user that is logged in
     */
    private IntUser user;
 
    /**
     * Log in procedure.
     * Logs the commited user in and redirects to website application if
     * access was granted. Otherwise redirects to an error page.
     * @param u user that should logged in
     * @return  link path for website redirection
     */
    public String login(IntUser u) {
        user = dbC.findIntUser(u);
        System.out.println(u.getUsername());
        System.out.println(u.getPassword());

        if(user != null) {
            return "LOGIN_SUCCEEDED";
        }
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, Names.MSG_LOGIN_FAILED, ""));
        return "LOGIN";
    }

    /**
     * Logs an user out from the website.
     */
    public void logout() {
        user = null;
    }

    /**
     * Checks if an user is logged in.
     * @return  'true' if an user is logged in, 'false' if not
     */
    public boolean isLoggedIn() {
       return user!=null;
    }

    /**
     * Provides the current user that is logged in.
     * @return  current user
     */
    public String getCurrentUser() {
        return user.getUsername();
    }
}